
/************************************************************************
*************************************************************************
*************************************************************************
uk_transparency_appendix.do

Replicates tables and figures in appendix. Code appears in order of
exhibit (Table 1, Figure 2, ...)

Note that figures that are simple images (eg. Figure 1) are not
reproduced.
*************************************************************************
*************************************************************************
************************************************************************/






/************************************************************************
*************************************************************************
Preparation
*************************************************************************
************************************************************************/

//SET THIS TO POINT TO THE FOLDER CONTAINING THIS FILE
cap cd "D:\Dropbox\projects\jobcardcorruption\analysis\uk_rejres\replication"






do "do/ajayrd.ado"

global bw 15.611
global stars * 0.10 ** 0.05 *** 0.01

global permB = 300


cap mkdir ukresults
cap mkdir ukresults/regressions
cap mkdir ukresults/graphs
cap mkdir ukresults/tables
cap mkdir ukresults/newmech



/************************************************************************
*************************************************************************
Table A1
*************************************************************************
************************************************************************/
use "dta/uk_rd_dataset_alldetails_rescrape_acel2017.dta", clear

keep if rank == 1
geodist cen_lat cen_lon 30.293246 78.055879, gen(dist_dehradun)
gen cafe = cen_cybercaf_dist < 1 if cen_cybercaf_dist < .


gen litrate = cen_pc11_pca_p_lit/cen_poptot
gen sctfrac = (cen_pc11_pca_p_sc + cen_pc11_pca_p_st)/cen_poptot
egen bid = group(district block)


keep if abs(rvlev) < $bw

quietly: reghdfe zndays2018_rescrape avg_zndays2018_rescrape  cen_lightdv2011 dist_dehradun litrate sctfrac cen_borderdist cafe cen_hqdist_subdistrict cen_hqdist_district , vce(robust) absorb(bid)
keep if e(sample)

eststo clear
eststo: reg zndays2018_rescrape cafe avg_zndays2018_rescrape  , robust 
eststo: reg zndays2018_rescrape cafe avg_zndays2018_rescrape cen_lightdv2011 , robust 
eststo: reg zndays2018_rescrape cafe avg_zndays2018_rescrape cen_lightdv2011 cen_borderdist dist_dehradun cen_hqdist_subdistrict cen_hqdist_district , robust 
eststo: reg zndays2018_rescrape cafe avg_zndays2018_rescrape cen_lightdv2011 cen_borderdist  dist_dehradun cen_hqdist_subdistrict cen_hqdist_district litrate sctfrac , robust 

reghdfe zndays2018_rescrape avg_zndays2018_rescrape  cen_lightdv2011 dist_dehradun litrate sctfrac cen_borderdist cafe cen_hqdist_subdistrict cen_hqdist_district , vce(robust) absorb(bid)
estadd local fes = "X"
eststo

#d;
esttab , 
		b(3) se(3)  star(* 0.10 ** 0.05 *** 0.01)  noobs 
		sca("N Observations" "fes Block FEs") nonote 
		sfmt("%9.0f" "%9.0g" "%9.0g")  mtitle("Days of Labor for President")
		varlabel(cafe "Near Cafe"  avg_zndays2018_rescrape "Avg. Days" cen_lightdv2011 "2011 Night Lights" cen_borderdist  "Distance to Border" dist_dehradun "Distance to Dehradun" cen_hqdist_subdistrict "Distance to Sub-Dist HQ" cen_hqdist_district "Distance to District HQ" litrate "Literacy" sctfrac "SCT Fraction" _cons "Constant") 
	;
#d cr


tempfile blah
#d;
esttab using `blah', 
		b(3) se(3)  star(* 0.10 ** 0.05 *** 0.01)  noobs  tex
		sca("N Observations" "fes Block FEs") nonote 
		sfmt("%9.0f" "%9.0g" "%9.0g")  mtitle("Days of Labor for President")
		varlabel(cafe "Near Cafe"  avg_zndays2018_rescrape "Avg. Days" cen_lightdv2011 "2011 Night Lights" cen_borderdist  "Distance to Border" dist_dehradun "Distance to Dehradun" cen_hqdist_subdistrict "Distance to Sub-Dist HQ" cen_hqdist_district "Distance to District HQ" litrate "Literacy" sctfrac "SCT Fraction" _cons "Constant") 
	;
#d cr

filefilter "`blah'" "ukresults/newmech/cafe_robust.tex", from("\BSmulticolumn{1}{c}{Days of Labor for President}&\BSmulticolumn{1}{c}{est2}&\BSmulticolumn{1}{c}{est3}&\BSmulticolumn{1}{c}{est4}&\BSmulticolumn{1}{c}{est5}") to("\BSmulticolumn{5}{c}{Days of Labor for President}") replace




/************************************************************************
************************************************************************
Figures A1 and A2
************************************************************************
************************************************************************/

local lab0 "a.   Cafe Far Away (>5km)"
local lab1 "b.   Cafe Nearby (<5km)"


use "dta/uk_rd_dataset_alldetails_rescrape.dta", clear

keep if district != "हरिद्वार"


gen cafe = cen_cybercaf_dist < 1 if cen_cybercaf_dist < .


keep pid rank rvlev zndays*_rescrape cafe
rename *_rescrape *
reshape long zndays, i(pid rank) j(year)
drop if year == 2019
keep if year >= 2011

tab year, gen(IND)
drop IND3

keep if abs(rvlev) < ${bw}

foreach cafe in 0 1 {
	local graphlist
	foreach year of numlist 2013/2018 {
		preserve 	
		keep if cafe == `cafe'
		keep if year == `year'
		
		#d;
		ajayrd zndays rvlev, bw(${bw}) xtitle("Vote Margin (Number of Votes)", size(small)) ytitle("Days of Labor (`year')", size(small))
				name(g`year') title("`year'", size(medlarge) ) nooffset
				discpos(80 -6) estpos(80 9) binsize(1) cluster(pid)
				ylabel(-15(15)90) xlabel(-16(8)16)
				;
		#d cr
		local graphlist `graphlist' g`year'
		restore
	}
	
	graph combine `graphlist', graphregion( color(white) fcolor(white) lcolor(white)) title("`lab`cafe''")
	graph drop `graphlist'
	
	graph export "ukresults/graphs/appendix_yearbyyear_cafe`cafe'.pdf", replace
}







/************************************************************************
************************************************************************
Table A2
************************************************************************
************************************************************************/

use "dta/ukgpdetail2014.dta"  , clear
collapse (count) ncand=nvotes, by(pid)


tempfile ncand
save `ncand'

local cutoff 1

use "dta/uk_rd_dataset_census_v1.dta", clear
merge m:1 pid using `ncand'
drop if _m==2
drop _m



keep pid aggnvotes aggnrej aggntot avg_zndays2013 cen_* ncand
duplicates drop
duplicates report pid



foreach type in cybercaf postoff majorroad bank market {
	gen `type' = cen_`type'_dist < `cutoff' if cen_`type'_dist < .
}

gen towndist = cen_pc01_vd_dist_town 
gen hqdist = cen_hqdist_district 
gen scfrac = cen_pc11_pca_p_sc/cen_pc11_pca_tot_p
gen litfrac = cen_pc11_pca_p_lit/cen_pc11_pca_tot_p
gen totpop = cen_pc11_pca_tot_p
gen nschools = cen_nschools

//Different election officers interpreted "total" votes differently
//We'll define our own measure
egen final_tot_votes = rowtotal( aggnvotes aggnrej )
gen fracrej = aggnrej / final_tot_votes



label var cybercaf	"Near Cyber Cafe"
label var postoff	"Near Post Office"
label var majorroad	"Near Major Road"
label var bank		"Near Bank"
label var market	"Near Market"

label var towndist "Dist. to town"
label var hqdist "Dist. to HQ"
label var scfrac "SC Frac."
label var litfrac "Frac. Literate"
label var totpop "Tot. Pop"
label var nschools "Primary Schools"


label var fracrej "Fraction of Votes Rejected"
label var ncand "Number of Candidates"

gen near_cybercaf = cybercaf==1 if !mi(cybercaf)
gen far_cybercaf = cybercaf==0 if !mi(cybercaf)


collect clear
local count 0
foreach var of varlist postoff- nschools fracrej ncand {
	
	reg `var' far_cybercaf near_cybercaf, robust noconstant
	test far_cybercaf = near_cybercaf
	collect get Far = _b[far_cybercaf] Near=_b[near_cybercaf] Diff=(_b[near_cybercaf]-_b[far_cybercaf]) P_val=r(p)
	
	local ++count
	local tmp : var label `var'
	collect label levels cmdset `count' "`tmp'", modify
}


collect style cell result[Far Near Diff ], nformat(%8.2f)
collect style cell result[P_val ], nformat(%8.2f)

collect layout (cmdset) (result)

collect export "ukresults/regressions/appendix_cafebalance.tex", replace tableonly










/************************************************************************
************************************************************************
Figure A3
************************************************************************
************************************************************************/

use "dta/uk_extendedfam_dataset.dta", clear

keep if district != "हरिद्वार"


local out zndays2015

/*******
Labels
*******/
local bw0 15
local bw1 12.5
local bw2 10

foreach bwind in 0 1 2 {
	

	preserve
	
	keep if iscandidate == 0
	
	#d;
	ajayrd `out' rvlev, bw(`=`bw`bwind''+.1') xtitle("Vote Margin (Number of Votes)", size(vlarge)) ytitle("Days of Labor (2015)", size(vlarge))
			name(g`bwind') title("BW=`bw`bwind''", size(huge) ) nooffset
			discpos(60 -`=`bw`bwind''/1.5') estpos(60 -2) binsize(1) cluster(pid)
			ylabel(0(15)75) xlabel(-`bw`bwind''(5)`bw`bwind'')
			;
	#d cr
	

	restore
}


graph combine g0 g1 g2, graphregion( color(white) fcolor(white) lcolor(white)) xsize(8) rows(1) ysize(3)
graph drop g0 g1 g2

graph export "ukresults/graphs/factions.pdf", replace






/************************************************************************
************************************************************************
Table A3
************************************************************************
************************************************************************/

eststo clear

use "dta/uk_extendedfam_dataset.dta", clear
gen pos = rvlev > 0
 

gen candfam = iscandidate == 0

reg zndays2015 iscandidate c.iscandidate#(c.rvlev##c.pos) c.candfam#(c.rvlev##c.pos) if abs(rvlev) < ${bw}, cluster(pid)
estadd scalar conmean = _b[_cons]
eststo

reg zndays2015 iscandidate c.iscandidate#(c.rvlev##c.pos) c.candfam#(c.rvlev##c.pos) if abs(rvlev) <= 12.5, cluster(pid)
estadd scalar conmean = _b[_cons]
eststo

reg zndays2015 iscandidate c.iscandidate#(c.rvlev##c.pos) c.candfam#(c.rvlev##c.pos) if abs(rvlev) <= 10, cluster(pid)
estadd scalar conmean = _b[_cons]
eststo

#d;
esttab , 
		b(3) se(3)  star(* 0.10 ** 0.05 *** 0.01)  noobs 
		sca("conmean Outcome at Disc." "N Observations" "N_clust Panchayats") nonote 
		sfmt("%9.3f" "%9.0g" "%9.0g")  keep(c.iscandidate#c.pos c.candfam#c.pos  ) 
		order(c.iscandidate#c.pos c.candfam#c.pos  )
		varlabel(c.iscandidate#c.pos "--Candidate" c.candfam#c.pos "--Family"  ) 
		refcat(c.iscandidate#c.pos "RD Estimate:"  , nolabel)
		mtitles(
			"BW=15"
			"BW=12.5"
			"BW=10"

			)
			
	;
	
esttab 
using "ukresults/regressions/family.tex", 
		b(3) se(3)  star(* 0.10 ** 0.05 *** 0.01)  noobs replace
		sca("conmean Outcome at Disc." "N Observations" "N_clust Panchayats") nonote 
		sfmt("%9.3f" "%9.0g" "%9.0g")  keep(c.iscandidate#c.pos c.candfam#c.pos  ) 
		order(c.iscandidate#c.pos c.candfam#c.pos  )
		varlabel(c.iscandidate#c.pos "--Candidate" c.candfam#c.pos "--Family"  ) 
		refcat(c.iscandidate#c.pos "RD Estimate:"  , nolabel)
		mtitles(
			"BW=15"
			"BW=12.5"
			"BW=10"

			)
			
	;

#d cr








/************************************************************************
************************************************************************
Table A4
************************************************************************
************************************************************************/



/***********
Identify and drop candidates
*************/
use "dta/uk_rd_dataset_alldetails_rescrape", clear
keep jobcardno
tempfile candjobcard
save `candjobcard'

use "dta/hhbyyearlabor", clear
recode ndays* (.=0)

merge 1:1 jobcardno using `candjobcard'
drop if _m == 3
drop _m
/*

    Result                      Number of obs
    -----------------------------------------
    Not matched                     1,054,787
        from master                 1,054,787  (_merge==1)
        from using                          0  (_merge==2)

    Matched                             1,650  (_merge==3)
    -----------------------------------------
*/


/***********
Construct average days of labor by caste group
*************/
collapse ndays2015 ndays2016, by(category panchayat block district)
reshape wide @ndays2015 @ndays2016, i(panchayat block district) j(category) string

//Note that missing values here imply there are no job cards of that group in the panchayat
tempfile alloc_by_group
save `alloc_by_group'



/***********
Merge in
*************/
use "dta/uk_rd_dataset_alldetails_rescrape", clear
merge m:1 panchayat block district using `alloc_by_group'
/*

    Result                      Number of obs
    -----------------------------------------
    Not matched                         6,246
        from master                         0  (_merge==1)
        from using                      6,246  (_merge==2)

    Matched                             1,650  (_merge==3)
    -----------------------------------------
*/

keep if _m == 3
drop _m



/***********
Own group allocation
*************/
forvalues y=2015/2016 {
	gen OWNdays`y' = .
	label var OWNdays`y' "Caste Group (`y')"
	
	label var zndays`y' "Self (`y')"
	foreach lev in OTH SC ST {
		replace OWNdays`y' = `lev'ndays2015 if category=="`lev'"
	}
	
}



/***********
Run regression
*************/
gen pos = rvlev > 0

label var pos "RD Estimate"

eststo clear
eststo: reg zndays2015 		c.rvlev##c.pos 	if abs(rvlev) < ${bw}					, cluster(pid)
eststo: reg OWNdays2015 		c.rvlev##c.pos 	if abs(rvlev) < ${bw}					, cluster(pid)
eststo: reg zndays2016 		c.rvlev##c.pos 	if abs(rvlev) < ${bw}					, cluster(pid)
eststo: reg OWNdays2016 		c.rvlev##c.pos 	if abs(rvlev) < ${bw}					, cluster(pid)

esttab, b(2) se(2)  star(${stars}) label keep(pos) sca("N_clust Clusters") sfmt("%9.0f") nonote


esttab using "ukresults/regressions/appendix_castefavoritism.tex", b(2) se(2)  star(${stars}) label keep(pos) sca("N_clust Clusters") sfmt("%9.0f") nonote replace











/************************************************************************
************************************************************************
Table A5
************************************************************************
************************************************************************/


use "dta/uk_rd_dataset_alldetails_rescrape.dta", clear


/***********
Define cross-cuts
************/
gen fem 	= regexm(reseng,"Women")						if !mi(reseng)
gen caste 	= !(reseng=="Unreserved" | reseng=="Women")		if !mi(reseng)

label var fem	"Female Reservation"
label var caste	"Caste Reservation"



/***********
Regressions
************/
keep if district != "हरिद्वार"
gen pos = rvlev > 0 if rvlev < .

gen zndif = zndays2018_rescrape-zndays2015_rescrape



eststo clear
reg zndif 		c.rvlev##c.pos if abs(rvlev) < ${bw} & !mi(reseng)	, cluster(pid) 
estadd scalar conmean = _b[_cons]
eststo

local keeplist  pos  
local vlabels pos "RD Est."
local vlabels `vlabels' 
foreach var of varlist fem caste {
	reg zndif 		c.rvlev##c.pos##c.`var' if abs(rvlev) < ${bw}					, cluster(pid) 
	estadd scalar conmean = _b[_cons]
	eststo
	
	local keeplist  `keeplist' c.pos#c.`var'
	local labtmp: var label `var'
	local vlabels `vlabels' c.pos#c.`var' "RD Est. X `labtmp'"
}



#d;
esttab, b(3) se(3)  star(${stars})  noobs label
		sca("N Observations" "N_clust Clusters") nonote 
		sfmt("%9.0g" "%9.0g")  
		keep(`keeplist') varlabels(`vlabels')
			mgroups(
		"Change in NREGS Allocation, 2015 to 2018",
		pattern(1 0 0 0 0 0 ) prefix(\multicolumn{@span}{c}{) suffix(})   
		span erepeat(\cmidrule(lr){@span})
		) 
		
		nomtitles
;
#d cr


#d;
esttab using "ukresults/regressions/reservation_dynamic.tex", b(3) se(3)  star(${stars})  noobs label
		sca("N Observations" "N_clust Panchayats") nonote 
		sfmt("%9.0g" "%9.0g")  
		keep(`keeplist') varlabels(`vlabels')
			
			mgroups(
		"Change in NREGS Allocation, 2015 to 2018",
		pattern(1 0 0 ) prefix(\multicolumn{@span}{c}{) suffix(})   
		span erepeat(\cmidrule(lr){@span})
		) 
		
		nomtitles
		
		replace
;
#d cr




/************************************************************************
*************************************************************************
Figure A4
*************************************************************************
************************************************************************/


local labkharif "a.   Monsoon Season (Kharif)"
local labrabi 	"b.   Dry Season (Rabi)"

local outcome zndays

foreach season in kharif rabi {
	use "dta/uk_rd_dataset_`season'.dta", clear

	keep if district != "हरिद्वार"






	local out `outcome'2015


	#d;
	ajayrd `out' rvlev, bw(${bw}) xtitle("Vote Margin (Number of Votes)", size(vlarge)) ytitle("Days of Labor (`season')", size(vlarge))
			name(g`season') title("`lab`season''", size(huge) ) nooffset
			discpos(35 -12) estpos(35 -4) binsize(1) cluster(pid)
			ylabel(0(15)45) xlabel(-16(8)16)
			;
	#d cr

}


graph combine gkharif grabi, graphregion( color(white) fcolor(white) lcolor(white)) xsize(8)
graph drop gkharif grabi


graph export "ukresults/graphs/appendix_byseason.pdf", replace






/************************************************************************
************************************************************************
Table A6 and A7
************************************************************************
************************************************************************/

//We'll use two different definitions of distance
local threshold1 5km
local threshold2 10km
foreach cutoff in 2  {
	use "dta/uk_rd_dataset_alldetails_rescrape.dta", clear

	foreach type in cybercaf postoff majorroad bank market {
		gen `type' = cen_`type'_dist < `cutoff' if cen_`type'_dist < .
	}
	
	gen towndist = cen_pc01_vd_dist_town 
	gen hqdist = cen_hqdist_district 
	gen scfrac = cen_pc11_pca_p_sc/cen_pc11_pca_tot_p
	gen totpop = cen_pc11_pca_tot_p
	gen nschools = cen_nschools
	
	
	egen bid2 = group(district block)


	label var cybercaf	"Near Cyber Cafe"
	label var postoff	"Near Post Office"
	label var majorroad	"Near Major Road"
	label var bank		"Near Bank"
	label var market	"Near Market"
	
	label var towndist "Dist. to town"
	label var hqdist "Dist. to HQ"
	label var scfrac "SC Frac."
	label var totpop "Tot. Pop"
	label var nschools "Primary Schools"
	
	keep if district != "हरिद्वार"
	gen pos = rvlev > 0 if !mi(rvlev)

	gen zndif = zndays2018_rescrape-zndays2015_rescrape



	eststo clear
	
	reg zndif 		c.rvlev##c.pos if abs(rvlev) < ${bw} , cluster(pid) 
	estadd scalar conmean = _b[_cons]
	eststo
	
	reg zndif 		c.rvlev##c.pos if abs(rvlev) < ${bw} & !mi(cybercaf)	, cluster(pid) 
	estadd scalar conmean = _b[_cons]
	eststo

	reg zndif 		c.rvlev##c.pos##c.cybercaf if abs(rvlev) < ${bw}					, cluster(pid) 
	estadd scalar conmean = _b[_cons]
	eststo

	local keeplist  pos c.pos#c.cybercaf
	local vlabels pos "RD Est."
	local vlabels `vlabels' c.pos#c.cybercaf "RD Est. X Near Cyber Cafe"
	foreach var of varlist postoff majorroad bank market {
		reg zndif 		c.rvlev##c.pos##c.cybercaf `var' c.rvlev#c.`var' c.pos#c.`var' c.rvlev#c.pos#c.`var'	if abs(rvlev) < ${bw}					, cluster(pid) 
		estadd scalar conmean = _b[_cons]
		eststo
		
		local keeplist  `keeplist' c.pos#c.`var'
		local labtmp: var label `var'
		local vlabels `vlabels' c.pos#c.`var' "RD Est. X `labtmp'"
	}
	
	
	//All variables specification
	local var postoff majorroad bank market
	reg zndif 		c.rvlev##c.pos##c.cybercaf `var' c.rvlev#c.(`var') c.pos#c.(`var') c.rvlev#c.pos#c.(`var')	if abs(rvlev) < ${bw}					, cluster(pid) 
	estadd scalar conmean = _b[_cons]
	eststo


	#d;
	esttab, b(3) se(3)  star(${stars})  noobs label
			sca("N Observations" "N_clust Clusters") nonote 
			sfmt("%9.0g" "%9.0g")  
			keep(`keeplist') varlabels(`vlabels')
				mgroups(
			"Change in NREGS Allocation, 2015 to 2018",
			pattern(1 0 0 0 0 0 0 0) prefix(\multicolumn{@span}{c}{) suffix(})   
			span erepeat(\cmidrule(lr){@span})
			) 
			
			nomtitles
	;
	#d cr


	#d;
	esttab using "ukresults/regressions/cafe_horserace_by_within_`threshold`cutoff''.tex", b(3) se(3)  star(${stars})  noobs label
			sca("N Observations" "N_clust Panchayats") nonote 
			sfmt("%9.0g" "%9.0g")  
			keep(`keeplist') varlabels(`vlabels')
				
				mgroups(
			"Change in NREGS Allocation, 2015 to 2018",
			pattern(1 0 0 0 0 0 0) prefix(\multicolumn{@span}{c}{) suffix(})   
			span erepeat(\cmidrule(lr){@span})
			) 
			
			nomtitles
			
			replace
	;
	#d cr
	
	
	eststo clear
	reghdfe zndif 		c.rvlev##c.pos##c.cybercaf if abs(rvlev) < ${bw}					, cluster(pid) absorb(bid)
	estadd scalar conmean = _b[_cons]
	estadd local bfe			= "X"
	eststo

	local keeplist  pos c.pos#c.cybercaf
	local vlabels pos "RD Est."
	local vlabels `vlabels' c.pos#c.cybercaf "RD Est. X Near Cyber Cafe"
	foreach var of varlist towndist hqdist scfrac totpop nschools {
		reg zndif 		c.rvlev##c.pos##c.cybercaf `var' c.rvlev#c.`var' c.pos#c.`var' c.rvlev#c.pos#c.`var'	if abs(rvlev) < ${bw}					, cluster(pid)
		estadd scalar conmean = _b[_cons]
		eststo
		
		local keeplist  `keeplist' c.pos#c.`var'
		local labtmp: var label `var'
		local vlabels `vlabels' c.pos#c.`var' "RD Est. X `labtmp'"
	}
	
	//All variables specification
	local var towndist hqdist scfrac totpop nschools 
	reghdfe zndif 		c.rvlev##c.pos##c.cybercaf `var' c.rvlev#c.(`var') c.pos#c.(`var') c.rvlev#c.pos#c.(`var')	if abs(rvlev) < ${bw}					, cluster(pid) absorb(bid2)
	estadd scalar conmean = _b[_cons]
	estadd local bfe			= "X"
	eststo




	#d;
	esttab, b(3) se(3)  star(${stars})  noobs label
			sca("N Observations" "N_clust Clusters" "bfe Block FEs") nonote 
			sfmt("%9.0g" "%9.0g")  
			keep(`keeplist') varlabels(`vlabels')
				mgroups(
			"Change in NREGS Allocation, 2015 to 2018",
			pattern(1 0 0 0 0 0 0) prefix(\multicolumn{@span}{c}{) suffix(})   
			span erepeat(\cmidrule(lr){@span})
			) 
			
			nomtitles
	;
	#d cr
	
	

	#d;
	esttab using "ukresults/regressions/cafe_horserace2_by_within_`threshold`cutoff''.tex", b(3) se(3)  star(${stars})  noobs label
			sca("N Observations" "N_clust Clusters" "bfe Block FEs") nonote 
			sfmt("%9.0g" "%9.0g")  
			keep(`keeplist') varlabels(`vlabels')
				
				mgroups(
			"Change in NREGS Allocation, 2015 to 2018",
			pattern(1 0 0 0 0 0 0) prefix(\multicolumn{@span}{c}{) suffix(})   
			span erepeat(\cmidrule(lr){@span})
			) 
			
			nomtitles
			
			replace
	;
	#d cr
}





/************************************************************************
*************************************************************************
Figure A5
*************************************************************************
************************************************************************/



/************************************************************************
Control for audited [start calendar year of fiscal year]
************************************************************************/
use "dta/uk_social_audit.dta", clear

reshape long zndays audited auditedalt, i(pid rank) j(year)
drop if year == 2019
keep if year >= 2011

tab year, gen(IND)
drop IND3

keep if abs(rvlev) < ${bw}

recode audited auditedalt (.=0)

preserve 
		

	gen pos 		= rvlev > 0 if !mi(rvlev)
	gen rvlevXpos 	= rvlev*pos

	reg zndays c.cafe##c.(IND* rvlev rvlevXpos pos  (c.IND*)#c.(rvlev rvlevXpos pos )) audited c.audited#c.pos, clust(pid)

	clear


	set obs 8
	gen year 	= 2010 + _n
	gen b	 	= .
	gen se		= .

	foreach i of numlist 1/2 4/8 {
		
		replace b 	= _b[c.cafe#c.IND`i'#c.pos] 	if _n == `i'
		replace se 	= _se[c.cafe#c.IND`i'#c.pos] 	if _n == `i'
	}

	replace b		= 0						if _n == 3
	replace se		= 0						if _n == 3

	gen bu = b + invttail(e(df_r),.025)*se
	gen bl = b - invttail(e(df_r),.025)*se
	
	gen bu2 = b + invttail(e(df_r),.05)*se
	gen bl2 = b - invttail(e(df_r),.05)*se
	#d;
	twoway
		(rspike bu bl year, lc(purple%25) ) 
		(rspike bu2 bl2 year, lc(purple%50) ) 
		(scatter b year, mc(purple) ) 
		(scatteri 25 2016 25 2018, recast(area) color(ltblue%20) )
		(scatteri -125 2016 -125 2018, recast(area) color(ltblue%20) )
		,
			xline(2014, lp(dot) lc(red) ) text(-115 2014 "Election", color(red) ) 
			text(-110 2017 "Direct Routing" "Requirement", color(midblue) )
			graphregion(color(white) margin(b=-5) ) xtitle("") xscale(off) ytitle("Dif-in-Disc Estimate" "in GPs with Cafes vs. Without") 
			yline(0, lc(black) )   ylabel(-100(25)25) legend(off) /*name(g0)*/
			text(-75 2011 "Self-dealing" "(Excess Labor for President)", color(purple) placement(6) ) yscale(range(-125 25))
			name(control1) title("[Audit]=1 if Fiscal Year Begins in Calendar Year")
	;
	#d cr
restore



/************************************************************************
Control for audited [end calendar year of fiscal year]
************************************************************************/
use "dta/uk_social_audit.dta", clear


reshape long zndays audited auditedalt, i(pid rank) j(year)
drop if year == 2019
keep if year >= 2011

tab year, gen(IND)
drop IND3

keep if abs(rvlev) < ${bw}

recode audited auditedalt (.=0)

preserve 
		

	gen pos 		= rvlev > 0 if !mi(rvlev)
	gen rvlevXpos 	= rvlev*pos

	reg zndays c.cafe##c.(IND* rvlev rvlevXpos pos  (c.IND*)#c.(rvlev rvlevXpos pos )) audited c.auditedalt#c.pos, clust(pid)

	clear


	set obs 8
	gen year 	= 2010 + _n
	gen b	 	= .
	gen se		= .

	foreach i of numlist 1/2 4/8 {
		
		replace b 	= _b[c.cafe#c.IND`i'#c.pos] 	if _n == `i'
		replace se 	= _se[c.cafe#c.IND`i'#c.pos] 	if _n == `i'
	}

	replace b		= 0						if _n == 3
	replace se		= 0						if _n == 3

	gen bu = b + invttail(e(df_r),.025)*se
	gen bl = b - invttail(e(df_r),.025)*se
	
	gen bu2 = b + invttail(e(df_r),.05)*se
	gen bl2 = b - invttail(e(df_r),.05)*se
	#d;
	twoway
		(rspike bu bl year, lc(purple%25) ) 
		(rspike bu2 bl2 year, lc(purple%50) ) 
		(scatter b year, mc(purple) ) 
		(scatteri 25 2016 25 2018, recast(area) color(ltblue%20) )
		(scatteri -125 2016 -125 2018, recast(area) color(ltblue%20) )
		,
			xline(2014, lp(dot) lc(red) ) text(-115 2014 "Election", color(red) ) 
			text(-110 2017 "Direct Routing" "Requirement", color(midblue) )
			graphregion(color(white) margin(b=-5) ) xtitle("") xscale(off) ytitle("Dif-in-Disc Estimate" "in GPs with Cafes vs. Without") 
			yline(0, lc(black) )   ylabel(-100(25)25) legend(off) /*name(g0)*/
			text(-75 2011 "Self-dealing" "(Excess Labor for President)", color(purple) placement(6) ) yscale(range(-125 25))
			name(control2) title("[Audit]=1 if Fiscal Year Ends in Calendar Year")
	;
	#d cr
restore





graph combine control1 control2, rows(2) graphregion(color(white) fcolor(white) )
graph drop control1 control2

graph export "ukresults/graphs/appendix_audits1.pdf", replace





/************************************************************************
*************************************************************************
Figure A6
*************************************************************************
************************************************************************/


/************************************************************************
Drop if audited in 2017 or 2018
************************************************************************/
use "dta/uk_social_audit.dta", clear


drop if audited2017 == 1 | audited2018 == 1


reshape long zndays audited auditedalt, i(pid rank) j(year)
drop if year == 2019
keep if year >= 2011

tab year, gen(IND)
drop IND3

keep if abs(rvlev) < ${bw}

recode audited auditedalt (.=0)

preserve 
		

	gen pos 		= rvlev > 0 if !mi(rvlev)
	gen rvlevXpos 	= rvlev*pos

	reg zndays c.cafe##c.(IND* rvlev rvlevXpos pos  (c.IND*)#c.(rvlev rvlevXpos pos )) audited c.auditedalt#c.pos, clust(pid)

	clear


	set obs 8
	gen year 	= 2010 + _n
	gen b	 	= .
	gen se		= .

	foreach i of numlist 1/2 4/8 {
		
		replace b 	= _b[c.cafe#c.IND`i'#c.pos] 	if _n == `i'
		replace se 	= _se[c.cafe#c.IND`i'#c.pos] 	if _n == `i'
	}

	replace b		= 0						if _n == 3
	replace se		= 0						if _n == 3

	gen bu = b + invttail(e(df_r),.025)*se
	gen bl = b - invttail(e(df_r),.025)*se
	
	gen bu2 = b + invttail(e(df_r),.05)*se
	gen bl2 = b - invttail(e(df_r),.05)*se
	#d;
	twoway
		(rspike bu bl year, lc(purple%25) ) 
		(rspike bu2 bl2 year, lc(purple%50) ) 
		(scatter b year, mc(purple) ) 
		(scatteri 25 2016 25 2018, recast(area) color(ltblue%20) )
		(scatteri -125 2016 -125 2018, recast(area) color(ltblue%20) )
		,
			xline(2014, lp(dot) lc(red) ) text(-115 2014 "Election", color(red) ) 
			text(-110 2017 "Direct Routing" "Requirement", color(midblue) )
			graphregion(color(white) margin(b=-5) ) xtitle("") xscale(off) ytitle("Dif-in-Disc Estimate" "in GPs with Cafes vs. Without") 
			yline(0, lc(black) )   ylabel(-100(25)25) legend(off) /*name(g0)*/
			text(-75 2011 "Self-dealing" "(Excess Labor for President)", color(purple) placement(6) ) yscale(range(-125 25))
			name(drop1) title("Exclude GPs audited in 2017 or 2018")
	;
	#d cr
restore



/************************************************************************
Drop if audited in 2019
************************************************************************/
use "dta/uk_social_audit.dta", clear



drop if audited2019 == 1 

reshape long zndays audited auditedalt, i(pid rank) j(year)
drop if year == 2019
keep if year >= 2011

tab year, gen(IND)
drop IND3

keep if abs(rvlev) < ${bw}

recode audited auditedalt (.=0)

preserve 
		

	gen pos 		= rvlev > 0 if !mi(rvlev)
	gen rvlevXpos 	= rvlev*pos

	reg zndays c.cafe##c.(IND* rvlev rvlevXpos pos  (c.IND*)#c.(rvlev rvlevXpos pos )) audited c.auditedalt#c.pos, clust(pid)

	clear


	set obs 8
	gen year 	= 2010 + _n
	gen b	 	= .
	gen se		= .

	foreach i of numlist 1/2 4/8 {
		
		replace b 	= _b[c.cafe#c.IND`i'#c.pos] 	if _n == `i'
		replace se 	= _se[c.cafe#c.IND`i'#c.pos] 	if _n == `i'
	}

	replace b		= 0						if _n == 3
	replace se		= 0						if _n == 3

	gen bu = b + invttail(e(df_r),.025)*se
	gen bl = b - invttail(e(df_r),.025)*se
	
	gen bu2 = b + invttail(e(df_r),.05)*se
	gen bl2 = b - invttail(e(df_r),.05)*se
	#d;
	twoway
		(rspike bu bl year, lc(purple%25) ) 
		(rspike bu2 bl2 year, lc(purple%50) ) 
		(scatter b year, mc(purple) ) 
		(scatteri 25 2016 25 2018, recast(area) color(ltblue%20) )
		(scatteri -125 2016 -125 2018, recast(area) color(ltblue%20) )
		,
			xline(2014, lp(dot) lc(red) ) text(-115 2014 "Election", color(red) ) 
			text(-110 2017 "Direct Routing" "Requirement", color(midblue) )
			graphregion(color(white) margin(b=-5) ) xtitle("") xscale(off) ytitle("Dif-in-Disc Estimate" "in GPs with Cafes vs. Without") 
			yline(0, lc(black) )   ylabel(-100(25)25) legend(off) /*name(g0)*/
			text(-75 2011 "Self-dealing" "(Excess Labor for President)", color(purple) placement(6) ) yscale(range(-125 25))
			name(drop2) title("Exclude GPs audited in 2019")
	;
	#d cr
restore



graph combine drop1 drop2, rows(2) graphregion(color(white) fcolor(white) )
graph drop drop1 drop2

graph export "ukresults/graphs/appendix_audits2.pdf", replace







/************************************************************************
*************************************************************************
Figure A7
*************************************************************************
************************************************************************/


/*******************************************************************************
Draw sample of controls (with replacement)
*******************************************************************************/

use "dta/hhbyyearlabor.dta", clear
keep jobcardno panchayat district block ndays2015
foreach var of varlist ndays* {
	gen z`var' = `var'
	replace z`var' = 0 if mi(`var')
}

merge 1:1 jobcardno using "dta/uk_rd_dataset.dta"

rename (pid rvlev) cand_=
bysort panchayat district block: egen pid = mean(cand_pid)
bysort panchayat district block: egen rvlev = mean(cand_rvlev)

keep if !mi(pid)
drop if _m == 3

drop gender_candidate- _merge
//drop if rvlev < 0

//Randomly choose "control"
set seed 4037592
local B = ${permB}
forvalues r =1/`B' {
	gen draw = runiform()
	bysort pid (draw jobcardno): gen drawrank = _n
	gen con`r' = zndays2015 if drawrank == 1
	drop draw drawrank
}

collapse con*, by(pid)

gen simrank = 2

tempfile con
save `con'


/*******************************************************************************
True Estimate
*******************************************************************************/
use "dta/uk_rd_dataset.dta", clear

gen pos = rvlev > 0

reg zndays2015 		c.rvlev##c.pos 	if abs(rvlev) < ${bw}					, cluster(pid)
global btrue = _b[pos]

/*******************************************************************************
Version 1: Generate simulated losers
*******************************************************************************/

use "dta/uk_rd_dataset.dta", clear
keep if rvlev > 0

expand 2

bysort pid: gen simrank = _n
replace rvlev = -rvlev if simrank == 2

merge 1:1 pid simrank using `con'
/*


    Result                           # of obs.
    -----------------------------------------
    not matched                           887
        from master                       887  (_merge==1)
        from using                          0  (_merge==2)

    matched                               887  (_merge==3)
    -----------------------------------------

*/
drop if _m == 2

gen pos = rvlev > 0

tempfile est
cap postclose est
postfile est r b se df using `est'

local B = ${permB}
forvalues r =1/`B' {
	
	replace zndays2015 = con`r' if simrank == 2
	
	reg zndays2015 		c.rvlev##c.pos 	if abs(rvlev) < ${bw}					, cluster(pid)
	
	local b = _b[pos]
	local se = _se[pos]
	local df = e(df_r)
	
	post est (`r') (`b') (`se') (`df')
}

postclose est


use `est', clear

gen type = "simlose"


tempfile simlose
save `simlose'





/*******************************************************************************
Version 2: Generate simulated winners
*******************************************************************************/


use "dta/uk_rd_dataset.dta", clear
keep if rvlev < 0

expand 2

bysort pid: gen simrank = _n
replace rvlev = -rvlev if simrank == 2

merge 1:1 pid simrank using `con'
/*




    Result                           # of obs.
    -----------------------------------------
    not matched                         1,148
        from master                       887  (_merge==1)
        from using                        261  (_merge==2)

    matched                               887  (_merge==3)
    -----------------------------------------


*/
drop if _m == 2

gen pos = rvlev > 0

tempfile est
cap postclose est
postfile est r b se df using `est'

local B = ${permB}
forvalues r =1/`B' {
	
	replace zndays2015 = con`r' if simrank == 2
	
	reg zndays2015 		c.rvlev##c.pos 	if abs(rvlev) < ${bw}					, cluster(pid)
	
	local b = _b[pos]
	local se = _se[pos]
	local df = e(df_r)
	
	post est (`r') (`b') (`se') (`df')
}

postclose est


use `est', clear

gen type = "simwin"



/*******************************************************************************
Version 2: Generate simulated winners
*******************************************************************************/
append using `simlose'

sum b if type == "simlose", detail
local medsimlose = r(p50)

sum b if type == "simwin", detail
local medsimwin = r(p50)

#d;
twoway 
(kdensity b if type == "simlose") 
(kdensity b if type == "simwin")
,
text(.2 `medsimwin' "Replace Winner", color(maroon))
text(.2 `medsimlose' "Replace Loser", color(navy))
ylabel(0(.05).25) ysize(3)
graphregion(color(white)) legend(off)
xtitle("RD Coefficient: NREGA Days 2015")
ytitle("Density")

xline(${btrue}, lc(blue%20) lp(dash) )
text(.25 `=${btrue}-4' "True Estimate", color(blue%20))
;
#d cr

graph export "ukresults/graphs/appendix_permutation.pdf", replace













/************************************************************************
*************************************************************************
Figure A8
*************************************************************************
************************************************************************/

use "dta/uk_rd_dataset_alldetails_rescrape_moreperformance.dta", clear


bysort pid: keep if _N == 2

gen cafe = cen_cybercaf_dist < 1 if cen_cybercaf_dist < .

foreach stub in fracjobs SCTfracjobs FEMfracjobs fracmax {
	preserve
		keep pid rank rvlev `stub'* cafe
		
		local title : var label `stub'2014
		
		reshape long `stub' , i(pid rank) j(year)
		drop if year == 2019
		keep if year >= 2011

		tab year, gen(IND)
		drop IND3

		keep if abs(rvlev) < ${bw}

			 
		
		gen pos 		= rvlev > 0 if !mi(rvlev)
		gen rvlevXpos 	= rvlev*pos

		reg `stub' c.cafe##c.(IND*) if pos==1, clust(pid) 

		clear


		set obs 8
		gen year 	= 2010 + _n
		gen b	 	= .
		gen se		= .

		foreach i of numlist 1/2 4/8 {
			
			replace b 	= _b[c.cafe#c.IND`i'] 	if _n == `i'
			replace se 	= _se[c.cafe#c.IND`i'] 	if _n == `i'
		}



		replace b		= 0						if _n == 3
		replace se		= 0						if _n == 3

		gen bu = b + invttail(e(df_r),.025)*se
		gen bl = b - invttail(e(df_r),.025)*se

		gen bu2 = b + invttail(e(df_r),.05)*se
		gen bl2 = b - invttail(e(df_r),.05)*se
		#d;
		twoway
			(rspike bu bl year, lc(green%25) ) 
			(rspike bu2 bl2 year, lc(green%50) ) 
			(scatter b year, mc(green) ) 
			,
				xline(2014, lp(dot) lc(red) ) /*text(15 2014 "Election", color(red) placement(6) ) 
				text(15 2017 "Direct Routing" "Requirement", color(midblue) placement(6) )*/
				graphregion(color(white)  ) xtitle("Year of Labor Allocation" ) ytitle("Dif-in-Dif Estimate") 
				yline(0, lc(black) )    legend(off) name(`stub') title("`title'")
				/*text(15 2011 "Performance" "(Average Allocation to GP)", color(green) placement(6) ) yscale( range(0 1) ) */
		;
		#d cr
	restore
}


graph combine fracjobs SCTfracjobs FEMfracjobs fracmax , graphregion(color(white) fcolor(white)) cols(1) ysize(8)
graph drop fracjobs SCTfracjobs FEMfracjobs fracmax 

graph export "ukresults/graphs/appendix_moreperformance.pdf", replace










/************************************************************************
*************************************************************************
Figure A9
*************************************************************************
*************************************************************************/

/************************************************************************
Smoothed Histogram
*************************************************************************/
cap graph drop _all
use "dta/uk_rd_dataset.dta", clear
keep if abs(rvlev) <= 15
collapse (count) nobs=zndays2015, by(rvlev)


//Density
egen tot = total(nobs)
gen den = nobs/tot

#d;
twoway 
(bar den rvlev , fcolor(gs14) lcolor(gs16) ) 
(lpoly den rvlev if rvlev < 0, lc(black) ) 
(lpoly den rvlev if rvlev > 0, lc(black) )
,
graphregion(color(white)) legend(off) xtitle("Vote Margin (Levels)", size(huge) ) 
ylabel(0(.01).05) xlabel(-15(5)15) name(hist) ytitle("Probability Density", size(huge) )
;
#d cr



/************************************************************************
McCrary Test in Levels [Note: This is screwed up because we have no obs at 0]
*************************************************************************/

use "dta/uk_rd_dataset.dta", clear

preserve
keep if abs(rvlev) <= 50
DCdensity rvlev, breakpoint(0) generate(Xj Yj r0 fhat se_fhat) nograph //b(`binsize')
local est 	= string(r(theta),"%9.2f")
local se 	= string(r(se),"%9.2f")
local pval	= string(  2*( 1 - abs (   normal( r(theta) / r(se) )   ) ) , "%9.2f" )
restore


preserve
keep if abs(rvlev) <= 50

#delimit;
DCdensity rvlev, breakpoint(0) generate(Xj Yj r0 fhat se_fhat) //b(`binsize')
				graphopt(`" 
				ylabel(0(.02).06, labsize(large) )
				graphregion(color(white))
				xtitle("Vote Margin (Levels)", size(huge) )
				ytitle("Probability Density", size(huge) ) title("`title_`eltype''", size(huge) )
				text(.05 -32 "Log Difference:", size(vlarge) ) text(.05 12 "`est'", size(vlarge)) 
				text(.045 12 "(`se')", size(vlarge)) xlabel(-50(50)50, labsize(vlarge) ) name(mclev)

				"') 
				;
#delimit cr
restore





/************************************************************************
McCrary Test in percentages
*************************************************************************/
use "dta/uk_rd_dataset.dta", clear

preserve
keep if abs(rv) <= 50
DCdensity rv, breakpoint(0) generate(Xj Yj r0 fhat se_fhat) nograph //b(`binsize')
local est 	= string(r(theta),"%9.2f")
local se 	= string(r(se),"%9.2f")
local pval	= string(  2*( 1 - abs (   normal( r(theta) / r(se) )   ) ) , "%9.2f" )
restore


preserve
keep if abs(rv) <= 50

#delimit;
DCdensity rv, breakpoint(0) generate(Xj Yj r0 fhat se_fhat) //b(`binsize')
				graphopt(`" 
				
				graphregion(color(white))
				xtitle("Vote Margin (Proportion)", size(huge) )
				ytitle("Probability Density", size(huge) ) title("`title_`eltype''", size(huge) )
				text(14 -.050 "Log Difference:", size(vlarge) ) text(14 .02 "`est'", size(vlarge)) 
				text(13 .02 "(`se')", size(vlarge)) name(mcpct)

				"') 
				;
#delimit cr
restore




/************************************************************************
Combine
*************************************************************************/
graph combine hist mclev mcpct, rows(1) graphregion(color(white) fcolor(white)) xsize(9.3)
graph drop hist mclev mcpct

graph export "ukresults/graphs/density_checks.pdf", replace









/************************************************************************
************************************************************************
Tables A8 and A9
************************************************************************
************************************************************************/


//We'll use two different definitions of distance
local threshold1 5km
local threshold2 10km
foreach cutoff in 1 2 {
	use "dta/uk_rd_dataset_alldetails_rescrape.dta", clear

	gen towndist = cen_pc01_vd_dist_town 
	gen hqdist = cen_hqdist_district 
	gen scfrac = cen_pc11_pca_p_sc/cen_pc11_pca_tot_p
	gen totpop = cen_pc11_pca_tot_p
	gen nschools = cen_nschools
		
	
	foreach type in cybercaf postoff majorroad bank market {
		gen `type' = cen_`type'_dist < `cutoff' if cen_`type'_dist < .
	}


	label var cybercaf	"Near Cyber Cafe"
	label var postoff	"Near Post Office"
	label var majorroad	"Near Major Road"
	label var bank		"Near Bank"
	label var market	"Near Market"
	
	
	
	egen bid2 = group(district block)


	label var cybercaf	"Near Cyber Cafe"
	label var postoff	"Near Post Office"
	label var majorroad	"Near Major Road"
	label var bank		"Near Bank"
	label var market	"Near Market"
	
	label var towndist "Dist. to town"
	label var hqdist "Dist. to HQ"
	label var scfrac "SC Frac."
	label var totpop "Tot. Pop"
	label var nschools "Primary Schools"

	keep if district != "हरिद्वार"
	gen pos = rvlev > 0 if !mi(rvlev)

	gen zndif = zndays2018_rescrape-zndays2015_rescrape

	rdbwselect zndif rvlev, vce(cluster pid) kernel(uniform)	//Restricting to sample with non-missing cyber cafe yields same BW in practice
	local optbw = e(h_mserd)

	eststo clear
	
	reg zndif 		c.rvlev##c.pos if abs(rvlev) < `optbw' , cluster(pid) 
	estadd scalar conmean = _b[_cons]
	eststo
	
	reg zndif 		c.rvlev##c.pos if abs(rvlev) < `optbw' & !mi(cybercaf)	, cluster(pid) 
	estadd scalar conmean = _b[_cons]
	eststo

	reg zndif 		c.rvlev##c.pos##c.cybercaf if abs(rvlev) < `optbw'					, cluster(pid) 
	estadd scalar conmean = _b[_cons]
	eststo

	local keeplist  pos c.pos#c.cybercaf
	local vlabels pos "RD Est."
	local vlabels `vlabels' c.pos#c.cybercaf "RD Est. X Near Cyber Cafe"
	foreach var of varlist postoff majorroad bank market {
		reg zndif 		c.rvlev##c.pos##c.cybercaf `var' c.rvlev#c.`var' c.pos#c.`var' c.rvlev#c.pos#c.`var'	if abs(rvlev) < `optbw'					, cluster(pid) 
		estadd scalar conmean = _b[_cons]
		eststo
		
		local keeplist  `keeplist' c.pos#c.`var'
		local labtmp: var label `var'
		local vlabels `vlabels' c.pos#c.`var' "RD Est. X `labtmp'"
	}



	#d;
	esttab, b(3) se(3)  star(${stars})  noobs label
			sca("N Observations" "N_clust Clusters") nonote 
			sfmt("%9.0g" "%9.0g")  
			keep(`keeplist') varlabels(`vlabels')
				mgroups(
			"Change in NREGS Allocation, 2015 to 2018",
			pattern(1 0 0 0 0 0 0) prefix(\multicolumn{@span}{c}{) suffix(})   
			span erepeat(\cmidrule(lr){@span})
			) 
			
			nomtitles
	;
	#d cr


	#d;
	esttab using "ukresults/regressions/appendix_optbw_cafe_horserace_by_within_`threshold`cutoff''.tex", b(3) se(3)  star(${stars})  noobs label
			sca("N Observations" "N_clust Panchayats") nonote 
			sfmt("%9.0g" "%9.0g")  
			keep(`keeplist') varlabels(`vlabels')
				
				mgroups(
			"Change in NREGS Allocation, 2015 to 2018",
			pattern(1 0 0 0 0 0 0) prefix(\multicolumn{@span}{c}{) suffix(})   
			span erepeat(\cmidrule(lr){@span})
			) 
			
			nomtitles
			
			replace
	;
	#d cr
	
	
	eststo clear
	reghdfe zndif 		c.rvlev##c.pos##c.cybercaf if abs(rvlev) < `optbw'					, cluster(pid) absorb(bid)
	estadd scalar conmean = _b[_cons]
	estadd local bfe			= "X"
	eststo

	local keeplist  pos c.pos#c.cybercaf
	local vlabels pos "RD Est."
	local vlabels `vlabels' c.pos#c.cybercaf "RD Est. X Near Cyber Cafe"
	foreach var of varlist towndist hqdist scfrac totpop nschools {
		reg zndif 		c.rvlev##c.pos##c.cybercaf `var' c.rvlev#c.`var' c.pos#c.`var' c.rvlev#c.pos#c.`var'	if abs(rvlev) < `optbw'					, cluster(pid)
		estadd scalar conmean = _b[_cons]
		eststo
		
		local keeplist  `keeplist' c.pos#c.`var'
		local labtmp: var label `var'
		local vlabels `vlabels' c.pos#c.`var' "RD Est. X `labtmp'"
	}
	
	//All variables specification
	local var towndist hqdist scfrac totpop nschools 
	reghdfe zndif 		c.rvlev##c.pos##c.cybercaf `var' c.rvlev#c.(`var') c.pos#c.(`var') c.rvlev#c.pos#c.(`var')	if abs(rvlev) < `optbw'					, cluster(pid) absorb(bid2)
	estadd scalar conmean = _b[_cons]
	estadd local bfe			= "X"
	eststo




	#d;
	esttab, b(3) se(3)  star(${stars})  noobs label
			sca("N Observations" "N_clust Clusters" "bfe Block FEs") nonote 
			sfmt("%9.0g" "%9.0g")  
			keep(`keeplist') varlabels(`vlabels')
				mgroups(
			"Change in NREGS Allocation, 2015 to 2018",
			pattern(1 0 0 0 0 0 0) prefix(\multicolumn{@span}{c}{) suffix(})   
			span erepeat(\cmidrule(lr){@span})
			) 
			
			nomtitles
	;
	#d cr
	
	

	#d;
	esttab using "ukresults/regressions/appendix_optbw_cafe_horserace2_by_within_`threshold`cutoff''.tex", b(3) se(3)  star(${stars})  noobs label
			sca("N Observations" "N_clust Clusters" "bfe Block FEs") nonote 
			sfmt("%9.0g" "%9.0g")  
			keep(`keeplist') varlabels(`vlabels')
				
				mgroups(
			"Change in NREGS Allocation, 2015 to 2018",
			pattern(1 0 0 0 0 0 0) prefix(\multicolumn{@span}{c}{) suffix(})   
			span erepeat(\cmidrule(lr){@span})
			) 
			
			nomtitles
			
			replace
	;
	#d cr
}











/************************************************************************
*************************************************************************
Figure A10
*************************************************************************
************************************************************************/
 
cap graph drop _all

local colors orange green purple black
local count 0
local graphs
foreach bw in 22 16 12 8 {
	local ++count
	local col: word `count' of `colors'
	
	use "dta/uk_rd_dataset_alldetails_rescrape.dta", clear

	keep if district != "हरिद्वार"

	//bysort pid: keep if _N == 2

	gen cafe = cen_cybercaf_dist < 1 if cen_cybercaf_dist < .


	keep pid rank rvlev zndays*_rescrape cafe
	rename *_rescrape *
	reshape long zndays, i(pid rank) j(year)
	drop if year == 2019
	keep if year >= 2011

	tab year, gen(IND)
	drop IND3

	keep if abs(rvlev) <= `bw'


	preserve 
			

		gen pos 		= rvlev > 0 if !mi(rvlev)
		gen rvlevXpos 	= rvlev*pos

		reg zndays c.cafe##c.(IND* rvlev rvlevXpos pos  (c.IND*)#c.(rvlev rvlevXpos pos )), clust(pid)

		clear


		set obs 8
		gen year 	= 2010 + _n
		gen b	 	= .
		gen se		= .

		foreach i of numlist 1/2 4/8 {
			
			replace b 	= _b[c.cafe#c.IND`i'#c.pos] 	if _n == `i'
			replace se 	= _se[c.cafe#c.IND`i'#c.pos] 	if _n == `i'
		}

		replace b		= 0						if _n == 3
		replace se		= 0						if _n == 3

		gen bu = b + invttail(e(df_r),.025)*se
		gen bl = b - invttail(e(df_r),.025)*se
		
		gen bu2 = b + invttail(e(df_r),.05)*se
		gen bl2 = b - invttail(e(df_r),.05)*se
		
		if `bw' == 22 {
			local routetext text(-110 2017 "Direct Routing" "Requirement", color(midblue) )
			local electtext text(-115 2014 "Election", color(red) ) 
		}
		else {
			local routetext
			local electtext
		}
		
		#d;
		twoway
			(rspike bu bl year, lc(`col'%25) ) 
			(rspike bu2 bl2 year, lc(`col'%50) ) 
			(scatter b year, mc(`col') ) 
			(scatteri 25 2016 25 2018, recast(area) color(ltblue%20) )
			(scatteri -120 2016 -120 2018, recast(area) color(ltblue%20) )
			,
				xline(2014, lp(dot) lc(red) ) 
				`routetext' `electtext'
				graphregion(color(white)) xtitle("") xscale(off) /*ytitle("Dif-in-Disc Estimate" "in GPs with Cafes vs. Without") */ ytitle("")
				yline(0, lc(black) )   ylabel(-100 -50 25) legend(off) name(g`bw')
				text(-55 2011 "Self-dealing, BW=`bw'" "(Excess Labor for President)", color(`col') placement(6) ) yscale(range(-125 25))
		;
		#d cr
	restore
	
	local graphs `graphs' g`bw'
}

graph combine `graphs', graphregion(color(white) fcolor(white)) rows(`count') imargin(0 0 0 0) //xsize(8)
graph drop `graphs'

graph export "ukresults/graphs/appendix_difindisc_bw.pdf", replace
